added some development tools
[windows-sources.git] / developer / Samples / NET 4.6 / Samples for Parallel / ParallelExtensionsExtras / Extensions / DelegateExtensions.cs
blob05655c09e32149486ae600c67916904503a91cf8
1 //--------------------------------------------------------------------------
2 //
3 // Copyright (c) Microsoft Corporation. All rights reserved.
4 //
5 // File: DelegateExtensions.cs
6 //
7 //--------------------------------------------------------------------------
9 using System.Diagnostics;
10 using System.Linq;
12 namespace System
14 /// <summary>Parallel extensions for the Delegate class.</summary>
15 public static class DelegateExtensions
17 /// <summary>Dynamically invokes (late-bound) in parallel the methods represented by the delegate.</summary>
18 /// <param name="multicastDelegate">The delegate to be invoked.</param>
19 /// <param name="args">An array of objects that are the arguments to pass to the delegates.</param>
20 /// <returns>The return value of one of the delegate invocations.</returns>
21 public static object ParallelDynamicInvoke(this Delegate multicastDelegate, params object[] args)
23 if (multicastDelegate == null) throw new ArgumentNullException("multicastDelegate");
24 if (args == null) throw new ArgumentNullException("args");
25 return multicastDelegate.GetInvocationList()
26 .AsParallel().AsOrdered()
27 .Select(d => d.DynamicInvoke(args))
28 .Last();
31 /// <summary>
32 /// Provides a delegate that runs the specified action and fails fast if the action throws an exception.
33 /// </summary>
34 /// <param name="action">The action to invoke.</param>
35 /// <returns>The wrapper delegate.</returns>
36 public static Action WithFailFast(this Action action)
38 return () =>
40 try { action(); }
41 catch (Exception exc)
43 if (Debugger.IsAttached) Debugger.Break();
44 else Environment.FailFast("An unhandled exception occurred.", exc);
49 /// <summary>
50 /// Provides a delegate that runs the specified function and fails fast if the function throws an exception.
51 /// </summary>
52 /// <param name="function">The function to invoke.</param>
53 /// <returns>The wrapper delegate.</returns>
54 public static Func<T> WithFailFast<T>(this Func<T> function)
56 return () =>
58 try { return function(); }
59 catch (Exception exc)
61 if (Debugger.IsAttached) Debugger.Break();
62 else Environment.FailFast("An unhandled exception occurred.", exc);
64 throw new Exception("Will never get here");